/**
 * Copyright (c) 2006 RiseSoft Co.,Ltd  
 * $Header$
 */
package cn.newtest.bi.collection.model;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;

import net.risesoft.risebi.collection.commons.constants.SystemConstants;
import net.risesoft.risebi.commons.exception.SystemException;
import net.risesoft.risebi.commons.util.ExceptionUtil;
import net.risesoft.risebi.commons.util.PropsUtil;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;

/**
 * 开户用户表
 * 
 * @author <a href="mailto: chenjian@risesoft.net">陈健</a>
 * @version $Revision$
 * 
 */
@Entity
@org.hibernate.annotations.Entity(dynamicInsert=true,dynamicUpdate=true)
@Table(name="Rpt_User")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class User implements Comparable<Object>, Serializable {
	
	private static final Log log = LogFactory.getLog(User.class);
	
	private static final long serialVersionUID = -7967466084134482848L;
	
	public static final int USERTYPE_SYSTEMMANAGER = 1;
	public static final int USERTYPE_ENTERPRISEUSER = 2;

	@Id
	@Column(name="User_GUID",length=38)
	@GenericGenerator(name="User-assigned",strategy="assigned")
	private String guid;
	
	@Column(name="User_Name",length=50)
	private String name;
	
	@Column(name="User_RealName",length=50)
	private String realName;
	
	@Column(name="User_Password",length=40)
	private String password;
	
	/**
	 * 认证方式 1:数据库,2:LDAP,3:数字证书
	 */
	@Basic
	private Integer authentication_type;
	
	@Column(name="User_Email",length=50)
	private String email;
	
	@Column(name="User_Sex")
	private Integer sex;
	
	@Column(name="User_Phone",length=20)
	private String phone;
	
	@Column(name="User_Mobile",length=20)
	private String mobile;
	
	@Column(name="IsEnabled")
	private Boolean enabled;
	
	@Basic
	private Double tabIndex;
	
	@Transient
	private Boolean superAdmin;
	
	@Transient
	private Boolean serviceAdmin;
	
	/**
	 * 1：业务管理员 2：填报用户（企业用户）
	 */
	@Basic
	private Integer userType;
	

	
	/**
	 * 1:在线 2:离线 3:在线和离线
	 */
	@Basic
	private Integer openAccountType;
	

	
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="ParentUser_GUID",nullable=true)
	private User parentUser;
	
	@Column(name="User_UserKey",length=50)
	private String userkey;
	
	@OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.LAZY,mappedBy="parentUser")
	@OrderBy("tabIndex")
	private List<User> childUsers;
	
	/**
	 * 用户所拥有的roles
	 */
	@Transient
	private String[] roles;
	
	/**
	 * 用户访问时的IP
	 */
	@Transient
	private String ip;
	
	/**
	 * 管理用户所处的部门（包含父部门）
	 */
	@Transient
	private String[] departments;
	
	/**
	 * 企业用户（填报用户）所在的企业，是从动态表（catalog）中取出的，所以是map
	 */
	@Transient
	private Map enterprise;
	
	/**
	 * 用户进行报表查询时所选择的应用
	 */
	@Transient
	private Application defaultApp;
	
	/**
	 * 用户进行报表查询时所选择的服务
	 */
	@Transient
	private Service defaultService;
	
	@Transient
	public String getParentGuid() {
		if(parentUser != null){
			return parentUser.getGuid();
		}
		return "";
	}
	public void setParentGuid(String parentGuid) {
		if(parentGuid != null && parentGuid.trim().length()>0){
			if(parentUser==null){
				parentUser = new User();
			}
			parentUser.setGuid(parentGuid);
		}
	}
	
	@Transient
	public boolean isSuperAdmin(){
		if(superAdmin==null){
			String roleAdminGuid = null;
			try {
				roleAdminGuid = PropsUtil.getProperty(SystemConstants.REPORT_ROLEADMINGUID);
			} catch (SystemException e) {
				//ignored
			}
			String[] roles = this.getRoles();
			if(roles==null||roles.length==0){
				superAdmin = false;
				return false;
			}
			for(int i=0;i<roles.length;i++){
				if(roleAdminGuid.equals(roles[i])){
					superAdmin = true;
					return true;
				}
					
			}
			superAdmin = false;
			return false;
		}else{
			return superAdmin;
		}
	}
	
	@Transient
	public boolean isServiceAdmin(){
		if(serviceAdmin==null){
			String roleServiceAdminGuid = null;
			try {
				roleServiceAdminGuid = PropsUtil.getProperty(SystemConstants.REPORT_ROLESERVICEADMINGUID);
			} catch (SystemException e) {
				//ignored
			}
			String[] roles = this.getRoles();
			if(roles==null||roles.length==0){
				serviceAdmin = false;
				return false;
			}
			for(int i=0;i<roles.length;i++){
				if(roleServiceAdminGuid.equals(roles[i])){
					serviceAdmin = true;
					return true;
				}
					
			}
			serviceAdmin = false;
			return false;
		}else{
			return serviceAdmin;
		}
	}
	

	@Transient
	public String getInitialPassword(){
		try {
			return PropsUtil.getProperty(SystemConstants.REPORT_INITPASSWORD);
		} catch (Exception e) {
			log.error(ExceptionUtil.transformException(e));
			return "11111111";
		}
		
	}
	
	public String getUserkey() {
		return userkey;
	}

	public void setUserkey(String userkey) {
		this.userkey = userkey;
	}

	public User getParentUser() {
		return parentUser;
	}

	public void setParentUser(User parentUser) {
		this.parentUser = parentUser;
	}
	
	public List<User> getChildUsers() {
		return childUsers;
	}

	public void setChildUsers(List<User> childUsers) {
		this.childUsers = childUsers;
	}

	public Service getDefaultService() {
		return defaultService;
	}
	public void setDefaultService(Service defaultService) {
		this.defaultService = defaultService;
	}
	public Application getDefaultApp() {
		return defaultApp;
	}
	public void setDefaultApp(Application defaultApp) {
		this.defaultApp = defaultApp;
	}
	public Map getEnterprise() {
		return enterprise;
	}
	public void setEnterprise(Map enterprise) {
		this.enterprise = enterprise;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	
	public String[] getDepartments() {
		return departments;
	}
	public void setDepartments(String[] departments) {
		this.departments = departments;
	}
	public String[] getRoles() {
		return roles;
	}
	public void setRoles(String[] roles) {
		this.roles = roles;
	}
	
	
	
	public Integer getOpenAccountType() {
		return openAccountType;
	}
	public void setOpenAccountType(Integer openAccountType) {
		this.openAccountType = openAccountType;
	}
	
	public Integer getUserType() {
		return userType;
	}
	public void setUserType(Integer userType) {
		this.userType = userType;
	}
	
	public Integer getAuthentication_type() {
		return authentication_type;
	}
	public void setAuthentication_type(Integer authentication_type) {
		this.authentication_type = authentication_type;
	}
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	public String getGuid() {
		return guid;
	}
	public void setGuid(String guid) {
		this.guid = guid;
	}
	
	public Boolean getEnabled() {
		return enabled;
	}
	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}
	
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getPassword() {
		return this.password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	@Transient
	public String getEncryptPassword(){
		return this.password;
	}
	
	public boolean judgeInitialPassword() throws Exception {
		String ps = this.getPassword();
		if(ps.equals(PropsUtil.getProperty(SystemConstants.REPORT_INITPASSWORD)))
			return true;
		return false;
	}
	
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	public String getRealName() {
		return realName;
	}
	public void setRealName(String realName) {
		this.realName = realName;
	}
	
	public Integer getSex() {
		return sex;
	}
	public void setSex(Integer sex) {
		this.sex = sex;
	}
	
	public Double getTabIndex() {
		return tabIndex;
	}

	public void setTabIndex(Double tabIndex) {
		this.tabIndex = tabIndex;
	}
	
	/**
	 * @see java.lang.Comparable#compareTo(Object)
	 */
	public int compareTo(Object object) {
		User myClass = (User) object;
		return new CompareToBuilder().append(this.password, myClass.password).append(this.phone, myClass.phone).append(this.mobile, myClass.mobile).append(this.userType, myClass.userType).append(this.openAccountType, myClass.openAccountType)
				.append(this.realName, myClass.realName).append(this.sex, myClass.sex).append(this.authentication_type, myClass.authentication_type).append(this.enabled, myClass.enabled).append(this.guid, myClass.guid)
				.append(this.email, myClass.email).append(this.name, myClass.name).append(this.tabIndex, myClass.tabIndex).toComparison();
	}
	/**
	 * @see java.lang.Object#equals(Object)
	 */
	public boolean equals(Object object) {
		if (!(object instanceof User)) {
			return false;
		}
		User rhs = (User) object;
		return new EqualsBuilder().appendSuper(super.equals(object)).append(this.password, rhs.password).append(this.phone, rhs.phone).append(this.mobile, rhs.mobile).append(this.userType, rhs.userType).append(this.openAccountType, rhs.openAccountType)
				.append(this.realName, rhs.realName).append(this.sex, rhs.sex).append(this.authentication_type, rhs.authentication_type).append(this.enabled, rhs.enabled).append(this.guid, rhs.guid).append(this.email, rhs.email)
				.append(this.name, rhs.name).append(this.tabIndex, rhs.tabIndex).isEquals();
	}
	/**
	 * @see java.lang.Object#hashCode()
	 */
	public int hashCode() {
		return new HashCodeBuilder(-112249579, 600771915).appendSuper(super.hashCode()).append(this.password).append(this.phone).append(this.mobile).append(this.userType).append(this.openAccountType).append(this.realName).append(this.sex)
				.append(this.authentication_type).append(this.enabled).append(this.guid).append(this.email).append(this.name).append(this.tabIndex).toHashCode();
	}
	/**
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		return new ToStringBuilder(this).append("mobile", this.mobile).append("userType", this.userType).append("authentication_type", this.authentication_type).append("enabled", this.enabled).append("realName", this.realName).append("tabIndex",
				this.tabIndex).append("openAccountType", this.openAccountType).append("phone", this.phone).append("name", this.name).append("email", this.email).append("password", this.password).append(
				"sex", this.sex).append("guid", this.guid).toString();
	}
	
}